<?php

header("Content-type: application/xhtml+xml");

require_once('../lib/Smarty/Smarty.class.php');
require_once('../lib/HimaShare.php');
require_once('../lib/Schedule.php');
require_once('../lib/Util.php');
require_once('../lib/Constants.php');
require_once('../lib/Config.php');

$data   = make_page(array_merge($_GET, $_POST));
$smarty = new Smarty();
$smarty->assign($data);
$smarty->display($data['error_code'] ? 'error.tmpl' : 'add_hima_complete.tmpl');

function make_page ($params) {
    $data = array(
        'error_code' => 0
    );

    if (!validate_signature(array_merge($_GET, $_POST))) {
        $data['error'] = 1;
        return $data;
    }

    if (!isset($_GET['date']) || !is_date($_GET['date'])) {
        $data['error'] = 1;
        return $data;
    }

    $date = $_GET['date'];
    $user = $_GET['opensocial_owner_id'];

    $current_schedule = Schedule::get_list($user, $date, $date);

    $result = FALSE;
    if (!$current_schedule) {
        $schedule = new Schedule();
        $schedule->member_id  = $user;
        $schedule->start_date = $date;
        $schedule->end_date   = $date;
        $schedule->flag       = SCHEDULE_ALL;
        $result = $schedule->insert();
    }

    $friends     = HimaShare::get_friends($user);
    $schedules   = array();
    foreach ($friends as $id => $friend) {
        $schedule_list = Schedule::get_list($id, $date, $date);
        if (!$schedule_list) continue;
        $schedules = array_merge($schedules, $schedule_list);
    }

    $data['result']    = $result;
    $data['date']      = date_to_unix($date);
    $data['date_link'] = $date;
    $data['schedule']  = $schedule;
    $data['schedules'] = $schedules;
    $data['friends']   = $friend;
    $data['url_prefix'] = URL_PREFIX;


    $data['analytics']    = '<img src="' . googleAnalyticsGetImageUrl() . '" />'; // for google analytics

    return $data;
}

?>
